// app.js
import MPServerless from '@alicloud/mpserverless-sdk'

const mpserverless = new MPServerless(wx, {
    appId: 'wx057c1eb6a07d5c1b',
    spaceId: 'mp-44a1bb7e-1c1a-4ab5-b892-3e21a74a35f3',
    clientSecret: 'vXLIqHnITJvxAObrgw1FEA==',
    endpoint: 'https://api.next.bspapp.com'
});
App({
  mpserverless: mpserverless,
  onLaunch() {
    mpserverless.init();
    // 展示本地存储能力
    // const logs = wx.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // wx.setStorageSync('logs', logs)

    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //   }
    // })
  },
  globalData: {
    userInfo: null
  },
  // 获取openid
  getOpenId () {
    const openid = wx.getStorageSync('caipiao_openid')
    return new Promise((reslut) => {
      if (openid) {
        reslut(openid)
      } else {
        wx.showLoading({
          title: '登陆中',
        })
        mpserverless.user.getInfo().then(res => {
          // console.log('getOpenID', res)
          if (res.success) {
            const openid = res.result.user.oAuthUserId || ''
            wx.setStorage({ // 写入openid
              key:"caipiao_openid",
              data:openid,
              success: function() {
                console.log('写入openid成功')
              },
              fail: function() {
                wx.showToast({
                  title: '错误代码：openid',
                  icon: 'error'
                })
              }
            })
            reslut(openid)
          } else {
            wx.showToast({
              title: '登录失败，请检查网络',
              icon: 'none',
              duration: 3000
            })
          }
        }, () => {
          wx.showToast({
            title: '登录失败，请检查网络',
            icon: 'none',
            duration: 3000
          })
        }).finally(() => {
          wx.hideLoading()
        })
      }
    })
  },
})
